package handler

import (
	"encoding/base64"
	"git.oschina.net/fanbuchi/scf-server/domain"
	"git.oschina.net/fanbuchi/scf-server/rsa"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/http"
)

type RsaHandler struct {

}

// @Summary 创建rsa加密
// @Description 创建rsa加密
// @Tags rsa
// @Accept  json
// @Produce  json
// @Param   origin    query    string     true        "原始需加密内容" default(chengdukm@gmail.com)
// @Success 200 {object} domain.Rsp    "调用成功"
// @Router /rsa/create [post]
func ( handler*RsaHandler)Create(c *gin.Context){
	origin:=c.Query("origin")
	data, err := rsa.RsaEncrypt([]byte(origin))
	if err != nil {
		panic(err)
	}
	rsp:=domain.Rsp{Code:http.StatusOK,Data:base64.StdEncoding.EncodeToString(data)}
	c.JSON(http.StatusOK,rsp)
}



// @Summary 解密rsa
// @Description 解密rsa
// @Tags rsa
// @Accept  json
// @Produce  json
// @Param   sign     body    domain.Rsp     true        "sign"
// @Success 200 {object} domain.Rsp    "调用成功"
// @Router /rsa/validate [post]
func ( handler*RsaHandler)Validate(c *gin.Context){
	var params domain.Rsp
	if err := c.ShouldBindBodyWith(&params, binding.JSON); err != nil {
		c.JSON(http.StatusOK, domain.Rsp{Code:http.StatusBadRequest,Msg:err.Error()})
		return
	}
	signed,err:=base64.StdEncoding.DecodeString(params.Data.(string))
	if err != nil {
		panic(err)
	}
	origin,err:=rsa.RsaDecrypt(signed)
	if err != nil {
		panic(err)
	}
	rsp:=domain.Rsp{Code:http.StatusOK,Msg:string(origin)}
	c.JSON(http.StatusOK,rsp)
}

